#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
根据.proto文件生成的py，生成cpp的ros对接代码
"""

from PythonFileUtil import *

def generate_msg_cpp(out_dir, proto_file_name, pkg_name, class_names):
    """
    生成msg的ros对接代码
    """
    file_content = []
    file_content.append(replace_file_content(
        "templates/cpp/msg/msg_header.tpl", proto_file_name, pkg_name, ""))
   
    for c in class_names:
        file_content.append(replace_file_content(
            "templates/cpp/msg/msg_body.tpl", proto_file_name, pkg_name, c))
    file_content.append("}  // namespace ros\n")

    for c in class_names:
        file_content.append(replace_file_content(
            "templates/cpp/msg/msg_tail.tpl", proto_file_name, pkg_name, c))
    write_to_file('%s/%s.h' % (out_dir, proto_file_name), '\n'.join(file_content))

def generate_srv_cpp(out_dir, proto_file_name, pkg_name, class_names):
    """
    生成srv的ros对接代码
    """
    write_file_content('%s/%s.h' % (out_dir, proto_file_name),
                       "templates/cpp/srv/srv_boot.tpl", 
                       proto_file_name, pkg_name, proto_file_name)
    srv_classes = [proto_file_name + "Request", proto_file_name + "Response"]
    for cppClass in srv_classes:
        write_file_content('%s/%s.h' % (out_dir, cppClass),
                           "templates/cpp/srv/srv_body.tpl", 
                           proto_file_name, pkg_name, cppClass)

def generate_act_cpp(out_dir, proto_file_name, pkg_name, class_names):
    """
    生成action的ros对接代码
    """
    base_class_name = proto_file_name
    suffixes = ["Goal", "Feedback", "Result", "ActionGoal", "ActionFeedback", "ActionResult", "Action"]
    action_templates = {
        "Goal": "action_data.tpl",
        "Feedback": "action_data.tpl",
        "Result": "action_data.tpl",
        "ActionGoal": "action_goal.tpl",
        "ActionFeedback": "action_feedback.tpl",
        "ActionResult": "action_result.tpl",
        "Action": "action_boot.tpl"
    }

    for suffix in suffixes:
        class_name = base_class_name + suffix
        template_name = action_templates[suffix]
        write_file_content('%s/%s.h' % (out_dir, class_name),
                           "templates/cpp/action/%s" % template_name,
                           proto_file_name, pkg_name, class_name)

def generate_cpp_ros(out_dir, msg_type, proto_file_name, pkg_name, class_names):
    """
    生成ros对接代码的入口
    """
    if msg_type == 'msg':
        generate_msg_cpp(out_dir, proto_file_name, pkg_name, class_names)
    elif msg_type == 'srv':
        generate_srv_cpp(out_dir, proto_file_name, pkg_name, class_names)
    elif msg_type == 'action':
        generate_act_cpp(out_dir, proto_file_name, pkg_name, class_names)
    else:
        print("没有匹配的 msg_type")
        return False